package com.yyfax.ph.base;

/**
 * Created by lenovo on 2017/2/7.
 */

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import com.yyfax.common.CLog;
import com.yyfax.common.tools.IMMLeaks;
import com.yyfax.ph.common.GlobalVariableConfig;
import com.yyfax.ph.personal.authority.gesture.GesturesPresenter;
import com.yyfax.ph.personal.authority.gesture.ValidateGesturesActivity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * Created by HenryZhang on 2016/11/21.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 * <p>
 * http://www.jianshu.com/p/6b3b1449123b
 * <p>
 * 判断手势密码，甚至是自动弹出登录界面
 */
public class ActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
	private final static String TAG = "ActivityLifecycleCallbacks";

	private int count;
	private long beginTime;
	private static final int LOCK_TIME = 5 * 60 * 1000;

	/**
	 * https://gist.github.com/pyricau/4df64341cc978a7de414
	 * https://zhuanlan.zhihu.com/p/20828861
	 * https://github.com/square/leakcanary/issues/572
	 * https://github.com/square/leakcanary/issues/322
	 */
	@Override
	public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
		CLog.i(TAG, "Activity onCreated: " + activity.getClass().getSimpleName());

		//todo 需要观察Activity是否能正常使用，特别是有输入的地方；另外要考虑其设备兼容性
		final InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE);
		final Field mServedViewField;
		final Field mHField;
		final Method finishInputLockedMethod;
		final Method focusInMethod;
		try {
			mServedViewField = InputMethodManager.class.getDeclaredField("mServedView");
			mServedViewField.setAccessible(true);
			mHField = InputMethodManager.class.getDeclaredField("mServedView");
			mHField.setAccessible(true);
			finishInputLockedMethod = InputMethodManager.class.getDeclaredMethod("finishInputLocked");
			finishInputLockedMethod.setAccessible(true);
			focusInMethod = InputMethodManager.class.getDeclaredMethod("focusIn", View.class);
			focusInMethod.setAccessible(true);

			IMMLeaks.ReferenceCleaner cleaner =
					new IMMLeaks.ReferenceCleaner(inputMethodManager, mHField, mServedViewField, finishInputLockedMethod);
			View rootView = activity.getWindow().getDecorView().getRootView();
			ViewTreeObserver viewTreeObserver = rootView.getViewTreeObserver();
			viewTreeObserver.addOnGlobalFocusChangeListener(cleaner);

		} catch (Exception unexpected) {
			CLog.e(TAG, "Unexpected reflection exception", unexpected);
		}

	}

	@Override
	public void onActivityStarted(Activity activity) {
		String name = activity.getClass().getSimpleName();
		CLog.i(TAG, "Activity onStarted: " + name + ", count=" + count);
		if (count == 0) {
			if (!GlobalVariableConfig.isThirdPartyPageOpened() && YJPH.getInstance().getPreferenceManager().isLoginSuccess()
					&& GesturesPresenter.readStatus() && YJPH.getInstance().hadLockPattern()) {
				if (!"DisplayLeakActivity".equals(name) && System.currentTimeMillis() - beginTime >= LOCK_TIME)
					ValidateGesturesActivity.start(activity);
			}
		}
		count++;
	}

	@Override
	public void onActivityResumed(Activity activity) {
		CLog.i(TAG, "Activity onResumed: " + activity.getClass().getSimpleName());
	}

	@Override
	public void onActivityPaused(Activity activity) {
		CLog.i(TAG, "Activity onPaused: " + activity.getClass().getSimpleName());
	}

	@Override
	public void onActivityStopped(Activity activity) {
		CLog.i(TAG, "Activity onStopped: " + activity.getClass().getSimpleName());
		count--;
		if (count == 0) {
			beginTime = System.currentTimeMillis();
		}
	}

	@Override
	public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
		CLog.i(TAG, "Activity onSaveInstanceState: " + activity.getClass().getSimpleName());
	}

	@Override
	public void onActivityDestroyed(Activity activity) {
		CLog.i(TAG, "Activity onDestroyed: " + activity.getClass().getSimpleName());
	}
}
